<?php

namespace App\Http\Controllers;


use App\Models\RefundDetail;
use App\Notifications\WechatRobot;
use D1M\Payment\ShouQianBa\Constants\OrderType;
use D1M\Payment\ShouQianBa\Notification;
use Exception;
use Illuminate\Http\Request;

class ShouqianbaController
{

    /**
     * @param Request $request
     * @param Notification $notification
     * @param int $id 收钱吧支付单 ID
     * @return array
     */
    public function receiveNotification(Request $request,Notification $notification,int $id)
    {
        $content = $request->getContent();
        $notification->init($id, OrderType::REFUND, $content);

        // 验证通知数据的签名
        if (!$notification->verifySign()) {
            return $notification->failWithBadSign();
        }

        try {
            // 应用支付结果通知数据
            $data = $notification->getData();

            if($data['order_type']=='2'){ //订单类型，1 销售； 2 退款
                $refund = RefundDetail::find($id);
                if($data['order_status']=='4'){ //4：操作完成
                    if($refund->status!==1){
                        $refund->status = 1;
                        $refund->trade_no = $data['order_sn'];
                        $refund->fail_memo = '';
                        $tenders = [];
                        foreach ($data['tenders'] as $tender){
                            $tenders[] = [
                                'original_tender_sn'=>$tender['original_tender_sn'],
                                'amount'=>abs($tender['amount']),
                            ];
                        }
                        if($tenders){
                            $refund->tenders = json_encode($tenders);
                        }
                        $refund->save();
                    }
                }elseif($data['order_status']=='6'){ //6：操作失败
                    $refund->fail_memo = $data['tenders'][0]['reason'];
                    $refund->save();

                    $message = "收钱吧退款失败.refund_no:".$refund->refund_no.".errMsg:".$refund->fail_memo;
                    \Illuminate\Support\Facades\Notification::send('', new WechatRobot($message));
                }
            }

            return $notification->success();
        } catch (Exception $e) {
            return $notification->fail($e);
        }
    }

}